﻿'use strict';

// The top bucketList ViewModel with its observable collection and properties.
var bucketListViewModel = function () {
    // The viewmodel properties.
    var self = this;
    self.items = ko.observableArray([]);
    self.newBucketTitle = ko.observable("Type you new bucket item");
    
    // Property that holds the name of the sharepoint list.
    self.sharePointListName = "BucketList";

    // The viewmodel operations.
    // Initialize the viewmodel.
    // Load all bucket list items and fill the observable array of links.
    self.init = function () {
        // Set up a list and CAML query to retrieve the items from sharepoint.
        var list = web.get_lists().getByTitle(self.sharePointListName);
        var camlString =
            "<View>" +
                "<ViewFields>" +
                    "<FieldRef Name='ID' />" +
                    "<FieldRef Name='Author' />" +
                    "<FieldRef Name='Title' />" +
                    "<FieldRef Name='Done' />" +
                "</ViewFields>" +
                "<Query>" +
                    "<Where>" +
                        "<Eq><FieldRef Name='Author' LookupId='TRUE' /><Value Type='Integer'>" + user.get_id() + "</Value></Eq>" +
                     "</Where>" +
                 "</Query>" +
                 "<RowLimit>10</RowLimit>" +
             "</View>";

        var camlQuery = new SP.CamlQuery();
        camlQuery.set_viewXml(camlString);
        var itemsFromSharePoint = list.getItems(camlQuery);
        context.load(itemsFromSharePoint, "Include(Title, ID, Author, Done)");

        // Execute the query with all the previous  
        // options and parameters.
        // On succes set the retrieved items in the observable collection.
        context.executeQueryAsync(
            function (sender, arg) {

                // Fill the items observable array.
                var enumerator = itemsFromSharePoint.getEnumerator();
                while (enumerator.moveNext()) {
                    var item = enumerator.get_current();

                    // Fill the array.
                    self.items.push(new bucketItem( item.get_item("ID"),
                                                    item.get_item("Title"),
                                                    item.get_item("Done")
                                                 ));
                }

                // Bind the viewModel to the view.
                ko.applyBindings(self);

            }, onFailedAction
        );
    }

    // Item number funcion to add 1 to the current item nummer.
    self.itemNumber = function (index) {
        return index + 1;
    }

    // Create a bucket item.   
    self.createBucketItem = function () {
        // Get the sharepoint list.
        var list = web.get_lists().getByTitle(self.sharePointListName);

        // Create new bucket item.
        var itemCreateInfo = new SP.ListItemCreationInformation();
        var listItem = list.addItem(itemCreateInfo);

        // Set item values and save the bucket item in the sharepoint list.
        listItem.set_item('Title', self.newBucketTitle());
        listItem.update();

        // On succes push the item in the observable collection.
        context.executeQueryAsync(
            function (sender, args) {
                self.items.push(new bucketItem(listItem.get_id(),
                                               listItem.get_item("Title"),
                                               false
                                                )
                                    );
        },
        onFailedAction);
    }

    // Edit a bucket item.   
    self.editBucketItem = function (item) {
        // Get the sharepoint list.
        var list = web.get_lists().getByTitle(self.sharePointListName);

        // Update the item because the id is set.
        // Retrieve the exsisting item from sharepoint and start editting.
        var editItem = list.getItemById(item.id);

        // Load the editTiem into the sharepoint context.
        context.load(editItem);
        context.executeQueryAsync(
            function (sender, args) {
                // Set item values and save the item in the sharepoint list.
                editItem.set_item('Done', item.done());
                editItem.update();

                // On edit succes, nothing needs to happen at this point.
                context.executeQueryAsync(
                    function (sender, args) {
                    },
                    onFailedAction);
            },
            onFailedAction);

    }

    // Remove the bucket item from sharepoint list and from the collection.
    self.removeBucketItem = function (item) {
        // Remove the item from the sharepoint list.
        var list = web.get_lists().getByTitle(self.sharePointListName);
        var listItem = list.getItemById(item.id);
        listItem.deleteObject();

        context.executeQueryAsync(
            function (sender, args) {
                // Remove bucket item  from observable on succes of async delete from sharepoint list.
                self.items.remove(item);
            },
            onFailedAction);
    }

}

// A BucketList Item class to hold item information information.
var bucketItem = function (id, title, done) {
    var self = this;
    self.id = id;
    self.title = title;
    self.done = ko.observable(done);

    saveChanges = function () {
        return viewModel.editBucketItem(self);
    };

    // Auto-save when done changes
    self.done.subscribe(saveChanges);

}